/*
 * WebServer - mod_neko server for scores and datafiles
 *
 * Copyright 2008 James W. Hofmann
 *
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

class WebServer
{
	public inline static var curversion : Int = 3;
	
	public static function getnum() : Int
	{
		var now = Date.now();
		var curgame = querynumindex(GenNum.todaysindex(Date.now()));
		writecurrentgame(curgame);
		return curgame;
	}

	public static function querynumindex(indexnum : Int)
	{
		var result =
		neko.db.Manager.cnx.request(
		"SELECT gamenum FROM"
		+" GameNums WHERE "+
		"id = "+Std.string(indexnum)
		);		
		return result.getIntResult(0);
	}

    public static function dbconnect()
	{        
        // initialize the connection
        var useMysql = true;
		var cnx : neko.db.Connection;

		trace("connecting to "+CreepData.databasename+"@"+
		CreepData.databaselocale);

        if( !useMysql )
            cnx = neko.db.Sqlite.open("mydatabase_file.db");
        else {
            cnx = neko.db.Mysql.connect({ 
                host : CreepData.databaselocale,
                port : 3306,
                database : CreepData.databasename,
                user : CreepData.databaselogin,
                pass : CreepData.databasepass,
                socket : null
            });
        }
 
        neko.db.Manager.cnx = cnx;
        neko.db.Manager.initialize();
    }
	
    public static function db_initTable() 
	{
		CreepData.initTable(neko.db.Manager.cnx);
    }

	public static function getgame(gamenumber : Int)
	{
		trace("getting "+Std.string(gamenumber));
		var results =
		neko.db.Manager.cnx.request(
		"SELECT datafile, username, groupname, gamenumber FROM"
		+" CreepData WHERE gamenumber!="+
		getnum()+
		" AND id = "+Std.string(gamenumber)
		);
		trace(results.length);
		if (results.length>0)
		{
			var final = [results.getResult(0), 
						 Encoder.unencode(results.getResult(1)), 
						 Encoder.unencode(results.getResult(2)), 
						 results.getIntResult(3)];
			return haxe.Serializer.run(final);
		}
		else	
		{
			trace("i got nothing");
			return null;
		}
	}

	public static function savegame(serialized : String)
	{
		trace("audit!");
		var validnum = getnum();
		CreepData.auditGame(serialized, validnum);
	}

	public static function processindata(indata : StringBuf)
	{

		var str = indata.toString();
		if (str.length>0) // the only thing uploaded to the server
						  // is saved games, so we might as well try
						  // to treat them as such
		{
			savegame(str);
		}
	}

	static function main() 
	{

		var args = neko.Web.getParams();
		
		// format: "cmd=xxxx"
		
		switch(args.get("cmd"))
		{
			case("dailygame"):	
				CreepData.loadDbInfo();
				dbconnect();

				neko.Lib.print(Std.string(getnum()));
			case("getrecord"):	
				CreepData.loadDbInfo();
				dbconnect();
				var id = Std.parseInt(args.get('id'));
				updatedl(id);
				neko.Lib.print(getgame(id));
			case("storerecord"):
				CreepData.loadDbInfo();
				dbconnect();
				
				var data = neko.Web.getParams();
				var f = neko.io.File.write("/var/www/log",false);
				f.write(data.get("data"));
				f.close();

				savegame(data.get("data"));
				
			default:
				neko.Lib.println("<p>Space Creeps web server, format version "
				+curversion+"</p>");
				neko.Lib.println("<br \\>Commands: (GET cmd=)");
				neko.Lib.println("<br \\>dailygame: get today's game number");
				neko.Lib.println("<br \\>getrecord (+GET id=): get the datafile for a game recording");
				neko.Lib.println("<br \\>storerecord (+POST data=): validate and store the datafile"+
									   " for a game recording");
		}

		
		
	}

	public static function writecurrentgame(num : Int)
	{
		neko.db.Manager.cnx.request(
			"UPDATE Settings
			SET value="+Std.string(num)+
			" WHERE name='curgame'"
			);
		trace("updated today's game: "+Std.string(curgame));
	}

	public static function updatedl(recid : Int)
	{
		neko.db.Manager.cnx.request(
			"UPDATE CreepData "+ 
			"SET downloads=downloads+1 "+
			" WHERE id="+Std.string(recid)
			);
		trace("incremented download count");
	}
	
}
